#!/bin/sh
#
#    Copyright (C) 2009  Vitaly Druzhinin
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
#    On Debian systems, the complete text of the GNU General Public
#    License can be found in /usr/share/doc/flex-fw/GPL-3 file.
#
#    On Slackware systems, the complete text of the GNU General Public
#    License can be found in /usr/doc/flex-fw/GPL-3 file.
#

USERID=`id -u`
if test ! "$USERID" = "0"
then
    echo "Unsufficient privileges: you must became a root..."
    exit 1
fi

echo "Try to make the Debian package"

SRCDIR="./debian"
PKGNUM=1
VER=""
echo -n "Step 1: Get package version: "
if test -z "$VER"
then
    VER=`grep "^Version: \([0-9]\+\.\)\{2\}[0-9]\+" ./$SRCDIR/DEBIAN/control | cut -d " " -f 2`
    if test -z "$VER"
    then
        echo "Fail! Invalid package version from ./debian/DEBIAN/control!"
        exit 1
    fi
fi
echo "Done. Version $VER."


PKGNAME=flex-fw-$VER-$PKGNUM\_all.deb


echo -n "Step 2. Make temporary directory: "
TMPDIR=`mktemp -d`
if test $? -gt 0
then
    echo "Fail! Error creating temporary directory!"
    exit 1
fi

echo "Done. $TMPDIR created"


echo -n "Step 3. Copy source tree $SRCDIR to $TMPDIR: "
cp -ax $SRCDIR $TMPDIR
if test $? -gt 0
then
    echo "Fail! Check access rights or disk free space!"
    exit 1
fi
echo "Done."

echo -n "Step 4. Remove .svn: "
find $TMPDIR/debian -name '.*' -exec rm -rf {} \; >/dev/null 2>&1
echo "Done."

echo -n "Step 5. Remove backups: "
find $TMPDIR/debian -name '*~' -exec rm -rf {} \; >/dev/null 2>&1
echo "Done."

echo -n "Step 6. Set current version to $VER: "
sed -i "s/X\.X\.X/$VER/" $TMPDIR/debian/etc/flex-fw/vars/base/version
echo "Done."

echo -n "Step 7. Set permissions to root:root: "
chown -R root:root $TMPDIR/debian
echo "Done."

echo -n "Step 8. Make package $PKGNAME: "
dpkg --build $TMPDIR/debian $PKGNAME
echo "Done."

echo -n "Step 9. Remove $TMPDIR: "
rm -rf $TMPDIR
echo "Done."
